簡単に理解するPushNotification on Unity iOS
概要
iOS Push通知受け取り RTAする。
手順
Pusher.app を使ってローカル環境からAPNs(Apple Push Notification service)をぶっ叩いてpushを出す。
まず開発者ページからSSLのcertをつくるよ
https://developer.apple.com/account/resources/certificates/add
Apple Push Notification service SSL (Sandbox & Production)作成
ここを見ながら https://help.apple.com/developer-account/#/devbfa00fef7 request用のcsrを作成
生成したSSL証明書をDLしてkeychainに追加、対象の証明書を右クリック > ~を書き出す を選択。 これで、p12で署名した状態の証明書が作れる。
キーチェーンで作成したp12をPusher.appにセットすると、パスワード聞かれるので返答。無事に設定が完了すると、次のようなログが出る。
さて、これでpushの準備はできたので、push対象のtokenを取得する。実機に対してコードを追加しよう。
iOS用のUnityアプリをビルドし、Xcode上で無理やりUNUserNotificationCenter関連のコードを入れていく。
これから、push通知をAPNsに送り出す際にどの端末に送り出すかを決定する要素 = deviceTokenをiOS実機から取得する。
didRegisterForRemoteNotificationsWithDeviceToken メソッドはすでにUnityが書いてるので、そこにトークンを文字列表示するコードを書き足す。
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSUInteger length = deviceToken.length;
const unsigned char *buffer = (unsigned char*)deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
NSString *deviceTokenSt = [hexString copy];
NSLog(@"deviceToken:%@", deviceTokenSt);
....
おまえにpush通知送ろうとおもうんだけどそういうのやっていい?っていうリクエストをユーザーに出すコードを何処かに書く。
自分は面倒くさかったのでdidFinishLaunchの末尾あたりに書いた。
....
UNUserNotificationCenter* current = [UNUserNotificationCenter currentNotificationCenter];
[current requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert )
completionHandler:^(BOOL granted, NSError * _Nullable error) {
NSLog(@"comp! granted:%d error%@:", granted, error );
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];// このメソッドはメインスレッドでしか実行できないのでこの書き方が必須
});
}
}];
....
その上で、Xcodeで実行する環境をdev向けにすることでtokenが取得できた。通常はrelease向けになっていて、Edit Schemeからdev向けに設定できた。
他の方法あったっけ、、、
この操作をやらないと、ユーザーが通知をOKしても、didRegisterやfailなどのdeviceToken受け取りのメソッドが一切着火しない。つら。
そんで当然、iOSのビルド設定をReleaseからDebugに変更しないとtoken取得に失敗するのは、作成済みのSSL証明書がsandboxのものだったからに他ならない。はい。
結果
iOS実機から取得できたtest app dev環境のデバイストークン 64文字。
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
これをPusher.appに渡して実行してみたところ、問題なく実機にpushが届いた。一発で動くのやばない。素敵。
ここまでのRTAは30分。調べながら書くのしんど。
なんらかのAPNsをぶっ叩くサービスを使うのが普通なので、ぶっちゃけ概念の説明などに大変な労力を割くべきだな。
来年見て覚えてるかどうか果てしなく怪しい。